<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import { useMessage, NCard, NGrid, NGridItem, NResult, NSpin } from "naive-ui";
import statusCode from "../api/statusCode";
import { searchGoods, SearchResult } from "../api/goods";
import { onBeforeRouteUpdate } from "vue-router";
import router from "../router";

const message = useMessage();

const currentPage = ref(1);

const searchResults = reactive<SearchResult[]>([]);
const search = async ({ query, pageNum, pageSize }: { query: string; pageNum: number; pageSize: number}) => {
  try {
    const resp = await searchGoods({ searchString: query, pageNum, pageSize });

    if (resp.status === statusCode.SUCCESS) {
      return resp.data;
    } else if (resp.status === statusCode.EMPTY_SEARCH_RESULT) {
      // no matching result
      return [];
    } else {
      throw new Error(`错误码 ${resp.status}`);
    }
  } catch (error) {
    message.error("" + error);
    return [];
  }
};

const getSearchResult = async ({ query }: { query: string }) => {
  loading.value = true;
  const results = await search({ query, pageNum: currentPage.value, pageSize: 5 });

  searchResults.length = 0;
  searchResults.push(...results);
  hasResult.value = searchResults.length > 0;
  loading.value = false;
};

onMounted(async () => {
  const query = router.currentRoute.value.query.q ?? '';
  await getSearchResult({
    query: typeof query == 'string' ? query : query[0] ?? ''
  });
});

onBeforeRouteUpdate(async (to) => {
  const query = to.query.q ?? '';
  await getSearchResult({
    query: typeof query == 'string' ? query : query[0] ?? ''
  });
});

const loading = ref(false);
const hasResult = ref(true);

</script>

<template>
  <n-spin :show="loading">
    <n-grid
      v-if="hasResult"
      class="results"
      x-gap="24"
      y-gap="12"
      cols="2 s:3 m:4 l:4 xl:5"
      responsive="screen"
    >
      <n-grid-item
        v-for="i of searchResults"
        :key="i.product_id"
      >
        <n-card
          content-style="padding-bottom: 0; padding-top: 20px;"
          embedded
        >
          <template #cover>
            <router-link
              class="link"
              :to="{ name: 'product', params: { storeId: i.store_id, productId: i.product_id } }"
            >
              <img
                :src="i.img_path"
                :alt="i.product_name"
                height="220"
              >
            </router-link>
          </template>
          <template #footer>
            <router-link
              class="link"
              :to="{ name: 'store', params: { storeId: i.store_id } }"
            >
              <p class="store-name">
                {{ i.store_name }}
              </p>
            </router-link>
          </template>
          <p class="price">
            {{ i.unit_price }}
          </p>
          <router-link
            class="link"
            :to="{ name: 'product', params: { storeId: i.store_id, productId: i.product_id } }"
          >
            <p class="product-name">
              {{ i.product_name }}
            </p>
          </router-link>
        </n-card>
      </n-grid-item>
    </n-grid>

    <n-card v-else>
      <n-result
        status="warning"
        title="无相关结果"
        description="尝试更换搜索关键词后重试"
      />
    </n-card>
  </n-spin>
</template>

<style scoped>
.link {
  color: unset;
  font-size: unset;
  display: block;
  width: 100%;
  text-decoration: none;
}
.store-name {
  margin: 0;
  font-size: 16px;
}
.product-name {
  margin: 0;
  font-size: 16px;
  font-weight: normal;
}
.price::before {
  content: "￥";
}
.price {
  color: #e4393c;
  margin: 0;
  font-size: 20px;
  font-weight: bold;
}
</style>
